# -*- coding: utf-8 -*-
"""
========================================================================================================================
@project : AosSanic
@file: OAClient
@Author: mengying
@email: 652044581@qq.com
@date: 2022/4/3 10:20
@desc: O2OA的群组相关接口
========================================================================================================================
"""

from OAClient import O2OAClient
from config import config
from OAError import O2OAError
import requests, json
from o2oa.OAPerson import O2OAPerson
from o2oa.OAUtils import JsonRemover


class O2OAGroup(O2OAClient):
    """020A群组/权限管理"""

    def __init__(self):
        super(O2OAGroup, self).__init__()

    def create(self, group_name, desc=""):
        """
        @desc: 新建群组
        @params: group_name 群组名称
        @params： desc 功能描述
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group"

        data = {
            "personList": [],
            "groupList": [],
            "identityList": [],
            "unitList": [],
            "description": desc,
            "unique": "",
            "orderNumber": "",
            "id": "",
            "name": group_name,
            "control": {"allowEdit": True, "allowDelete": True}
        }
        response = requests.post(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']['id']

    def delete(self, group_id):
        """
        @desc: 删除群组
        @params: group_id create得到的id
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/" + group_id
        response = requests.delete(url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def read(self, group_id):
        """
        @desc: 获取群组的数据
        @params: group_id create得到的id
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/" + group_id
        response = requests.get(url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response['data']

    def list(self):
        """
        @desc: 获取群组的列表
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/list/(0)/next/10"
        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        count = response['count']

        # 如果比17就不发第二次
        if count <= 10:
            return response['data']

        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/list/(0)/next/{}".format(str(count))
        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response['data']


class O2OAGroupStaff(O2OAClient):
    """020A群组人员管理"""

    def __init__(self):
        super(O2OAGroupStaff, self).__init__()

    def create(self, group_id, person_id):
        """
        @desc: 给群组添加人员
        @params: group_id O2OAGroup.create得到的id
        @params: person_id 个人id
        """

        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/" + group_id
        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        data = response.get("data")

        person_info = O2OAPerson().read(person_id)
        not_need_field = ['woIdentityList', 'woRoleList', 'woGroupList', 'woPersonAttributeList', 'control']
        person_info = JsonRemover(person_info).remove_fields(not_need_field)

        data['personList'].append(person_id)
        data['woPersonList'].append(person_info)

        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/" + group_id
        response = requests.put(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response['data']["id"]

    def delete(self, group_id, person_id):
        """
        @desc: 删除组织人员
        @params: group_id O2OAGroup.create得到的id
        @params: person_id 个人id
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/group/" + group_id

        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        data = response.get("data")

        # 删除操作
        personList = data['personList']
        personList.pop(personList.index(person_id))

        woPersonList = data['woPersonList']
        for i, wo in enumerate(woPersonList):
            if person_id == wo.get('id'):
                woPersonList.pop(i)

        response = requests.put(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']["id"]


if __name__ == '__main__':
    # 创建群组
    # print(O2OAGroup().create(group_name="日志权限"))

    # 读取群组信息
    # print(O2OAGroup().read(group_id='c249462a-b9c8-41cc-b57e-afcf71b5a843'))

    # 读取群组全部消息
    # print(O2OAGroup().list())

    # 群组添加人员
    # print(O2OAGroupStaff().create(group_id="c249462a-b9c8-41cc-b57e-afcf71b5a843", person_id='a21cbff4-51fb-42fc-8510-cac7e8ccf467'))

    # 群组中删除人员
    print(O2OAGroupStaff().delete(group_id="c249462a-b9c8-41cc-b57e-afcf71b5a843",
                                  person_id='a21cbff4-51fb-42fc-8510-cac7e8ccf467'))
